/*
 * Step 3
 * - Fork
 *   - Child
 *     - Open File
 *     - Scan In Numbers
 *     - Sort Numbers
 * 	   - Write Numbers To Pipe
 * 	   - Exit
 *   - Parent
 *     - Wait For Child
 * 	   - Read Numbers From Pipe
 * 	   - Print Numbers
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define READ 0
#define WRITE 1
#define NUMS_PER_FILE 4

pid_t pid;
int status;

int upPipe[2];

int i;
int numbers[NUMS_PER_FILE];

void doChild();
void doParent();
int intcmp(const void *n1, const void *n2);

int main(int argc, char* argv[])
{
	printf("\nstarting step3.c\n");

	if(pipe(upPipe) < 0)
	{
		printf("\nFailed to pipe");
	}

	else if((pid = fork()) < 0)
	{
		perror("\nFailed to fork");
	}
	else if(pid)	// Parent
	{
		doParent();
	}
	else 			// Child
	{
		doChild();
	}

	return 0;
}


void doChild()
{
	FILE *file;

	close(upPipe[READ]);

	file = fopen("1.txt", "r");

	// Scan in numbers
	for(i = 0; i < NUMS_PER_FILE; i++)
	{
		fscanf(file, "%d", &numbers[i]);
	}

	qsort(numbers, NUMS_PER_FILE, sizeof(int), intcmp);

	for(i = 0; i < NUMS_PER_FILE; i++)
	{
		write(upPipe[WRITE], &numbers[i], sizeof(int));
	}

	close(upPipe[WRITE]);

	printf("\nchild done\n");
}

void doParent()
{
	close(upPipe[WRITE]);
		
	waitpid(pid, &status, 0);

	for(i = 0; i < NUMS_PER_FILE; i++)
	{
		read(upPipe[READ], &numbers[i], sizeof(int));
	}

	for(i = 0; i < NUMS_PER_FILE; i++)
	{
		printf("%d ", numbers[i]);
	}

	close(upPipe[READ]);

	printf("\nparent done\n");
}

int intcmp(const void *n1, const void *n2)
{
	const int *num1 = (const int *)n1;
	const int *num2 = (const int *)n2;
	return (*num1 < *num2) ? -1 : (*num1 > *num2);
}
